package com.ruoyi.web.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.enums.PaperStatusEnums;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.FileUploadUtils;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PaperCheckPass;
import com.ruoyi.system.service.IPaperCheckPassService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import okhttp3.*;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * checkpass论文Controller
 *
 * @author ruoyi
 * @date 2025-05-07
 */
@Controller
@RequestMapping("/system/pass")
public class PaperCheckPassController extends BaseController {

    private String prefix = "system/pass";

    private static final String ADMIN = "admin";

    @Autowired
    private IPaperCheckPassService paperCheckPassService;


    @Autowired
    private RestTemplate restTemplate;

    /**
     * userAgent
     */
    List<String> userAgents = Arrays.asList(
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
    );

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)  // 连接超时
            .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)     // 读取超时
            .build();

    @Autowired
    private Environment env;

    @RequiresPermissions("system:pass:view")
    @GetMapping()
    public String pass() {
        return prefix + "/pass";
    }

    /**
     * 查询checkpass论文列表
     */
    @RequiresPermissions("system:pass:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PaperCheckPass paperCheckPass) {
        SysUser sysUser = super.getSysUser();
        List<SysRole> roles = sysUser.getRoles();
        boolean isAdmin = false;
        for (SysRole role : roles) {
            String roleKey = role.getRoleKey();
            if (roleKey.equals(ADMIN)) {
                isAdmin = true;
                break;
            }
        }

        if (isAdmin) {
            startPageForSystem();
        } else {
            startPageForOrderPass();
            paperCheckPass.setUserId(sysUser.getUserId());
        }
        List<PaperCheckPass> list = paperCheckPassService.selectPaperCheckPassList(paperCheckPass);
        return getDataTable(list);
    }

    /**
     * 导出checkpass论文列表
     */
    @RequiresPermissions("system:pass:export")
    @Log(title = "checkpass论文", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PaperCheckPass paperCheckPass) {
        List<PaperCheckPass> list = paperCheckPassService.selectPaperCheckPassList(paperCheckPass);
        ExcelUtil<PaperCheckPass> util = new ExcelUtil<PaperCheckPass>(PaperCheckPass.class);
        return util.exportExcel(list, "checkpass论文数据");
    }

    /**
     * 新增checkpass论文
     */
    @RequiresPermissions("system:pass:add")
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存checkpass论文（含文件上传）
     *
     * @param paperTitle  论文名称（自动从文件名回填）
     * @param paperAuthor 论文作者
     * @param paperFile   上传的论文文件（仅支持.doc/.docx）
     */
    @RequiresPermissions("system:pass:add")
    @Log(title = "checkpass论文", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(
            @RequestParam("paperTitle") String paperTitle,
            @RequestParam("paperAuthor") String paperAuthor,
            @RequestParam("paperFile") MultipartFile paperFile) {
        try {
            // 1. 文件类型校验（前端已限制，后端二次验证）
            String fileName = paperFile.getOriginalFilename();
            Assert.isTrue(fileName.matches("^.*\\.(doc|docx)$"), "仅支持.doc/.docx格式文件");

            ThirdPartyResponse thirdPartyResponse = new ThirdPartyResponse();
            String fileId = this.callThirdPartyApi(paperAuthor, paperFile, thirdPartyResponse);
            String removeSuffixName = thirdPartyResponse.getFiles().get(0).getRemoveSuffixName();


            OrderApiResponse orderApiResponse = new OrderApiResponse();
            String payId = this.callCreateOrderApi(fileId, removeSuffixName, paperAuthor, orderApiResponse);
            String paperId = orderApiResponse.getData().getPapers().get(0).getPaperId();
            String selectedOrder = randomSelectOrderNumber(Arrays.asList(
                    "Y2594114426319746",
                    "Y2492499612169984",
                    "Y2590783091143293"
            ));
            QuickCheckApiResponse quickCheckApiResponse = new QuickCheckApiResponse();
            this.quickCheck(selectedOrder, payId, quickCheckApiResponse);


            PaperCheckPass paperCheckPass = new PaperCheckPass();
            paperCheckPass.setCheckPassFileId(fileId);
            paperCheckPass.setCheckPassPayId(payId);
            paperCheckPass.setPddOrderId(selectedOrder);
            SysUser sysUser = getSysUser();
            paperCheckPass.setUserId(sysUser.getUserId());
            paperCheckPass.setPaperId(paperId);
            paperCheckPass.setPaperTitle(paperTitle);
            paperCheckPass.setPapaerAuthor(paperAuthor);
            paperCheckPass.setPaperStatus(PaperStatusEnums.CHECKING.getCode());
            paperCheckPass.setCreatePayIdResult(JSON.toJSONString(orderApiResponse));
            paperCheckPass.setUploadFileResult(JSON.toJSONString(thirdPartyResponse));
            paperCheckPass.setQuickCheckResult(JSON.toJSONString(quickCheckApiResponse));
            Assert.isTrue(paperCheckPassService.insertPaperCheckPass(paperCheckPass) > 0, "insert db error");
            return AjaxResult.success();

        } catch (Exception e) {
            logger.error("system error: ", e);
            return AjaxResult.error("system error: " + e.getMessage());
        }
    }


    /**
     * 立即检测
     */
    private String quickCheck(String pddOrderId, String payId, QuickCheckApiResponse quickCheckApiResponse)
            throws Exception {
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); // 类型设置方式变更
        String url =
                "https://api.checkpass.net/an/checkorder/payOrder?_user_token=oh6bS11bYGhfw5GZOW68fbQrAAw%3D";

        // 添加 form-data 参数（完全保持原始错误键名）
        multipartBuilder.addFormDataPart("pay_id", payId);
        multipartBuilder.addFormDataPart("pay_type", "checktid:num");
        multipartBuilder.addFormDataPart("param[tids][0]", pddOrderId);

        Request.Builder builder = new Request.Builder();
        this.buildRequestHeaders(builder);
        // 构建请求对象（OkHttp3 的 Request 构建方式）
        Request request = builder
                .url(url)
                .post(multipartBuilder.build()) // 请求体构建方式变更
                .addHeader("User-Agent", "OkHttp/3.14.9")
                .build();
        Response response = okHttpClient.newCall(request).execute();
        Assert.notNull(response, "call quickCheck error,response must not be null");
        Assert.isTrue(response.isSuccessful(),
                "call quickCheck error,response must  be success!code:" + response.code());
        Assert.notNull(response.body(), "call quickCheck error,response.body must not be null");
        String body = response.body().string();
        Assert.notBlank(body, "call quickCheck error,response.body must not be blank");
        logger.info("call quickCheck,response.code:{},response.body:{}", response.code(), body);

        QuickCheckApiResponse currentResult = JSON.parseObject(body, QuickCheckApiResponse.class);
        Assert.notNull(currentResult, "quickCheckApiResponse must not be null");

        Assert.isTrue(StringUtils.isBlank(currentResult.getCode()) && StringUtils.isBlank(
                currentResult.getCodeMsg()) &&
                StringUtils.isNotNull(currentResult.getData()), "quickCheckApiResponse,data is null");
        // 检查业务数据是否完整（重点校验pay_id）
        QuickCheckData quickCheckData = currentResult.getData();
        Assert.notNull(quickCheckData, "quickCheckData must not be null");
        quickCheckApiResponse.setData(quickCheckData);
        return quickCheckData.getOid();
    }

    /**
     * 从订单号列表中随机挑选一个订单号
     *
     * @param orderNumbers 包含订单号的列表，不可为空或无元素
     * @return 随机挑选出的订单号
     * @throws IllegalArgumentException 当输入列表为空或null时抛出
     */
    public String randomSelectOrderNumber(List<String> orderNumbers) {
        if (orderNumbers == null || orderNumbers.isEmpty()) {
            throw new IllegalArgumentException("订单号列表不能为空");
        }
        Random random = new Random();
        int randomIndex = random.nextInt(orderNumbers.size());
        return orderNumbers.get(randomIndex);
    }


    /**
     * 调用创建订单接口
     *
     * @param fileId 第一个接口返回的文件ID
     */
    private String callCreateOrderApi(String fileId, String title, String author, OrderApiResponse apiResponse)
            throws Exception {
        // 构建 multipart/form-data 请求体（使用 OkHttp3 的 MultipartBody）
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); // 类型设置方式变更
        String url =
                "https://api.checkpass.net/an/checkorder/preCreateMulti?_user_token=oh6bS11bYGhfw5GZOW68fbQrAAw%3D";
        // 添加 form-data 参数（完全保持原始错误键名）
        multipartBuilder.addFormDataPart("good id", "124913");
        multipartBuilder.addFormDataPart("jane name", "checkpass");
        multipartBuilder.addFormDataPart("papers[0][file_fid]", fileId);
        multipartBuilder.addFormDataPart("papers[0][title]", title);
        multipartBuilder.addFormDataPart("papers[0][author]", author);
        multipartBuilder.addFormDataPart("papers[0][content_type]", "file_fid");

        // 构建请求对象（OkHttp3 的 Request 构建方式）
        Request.Builder builder = new Request.Builder();
        this.buildRequestHeaders(builder);

        Request request = builder
                .url(url)
                .post(multipartBuilder.build())
                .addHeader("User-Agent", "OkHttp/3.14.9")
                .build();
        Response response = okHttpClient.newCall(request).execute();
        Assert.notNull(response, "call create order error,response must not be null");
        Assert.isTrue(response.isSuccessful(),
                "call create order error,response must  be success!code:" + response.code());
        Assert.notNull(response.body(), "call create order error,response.body must not be null");
        String body = response.body().string();
        Assert.notBlank(body, "call create order error,response.body must not be blank");
        logger.info("call create order,response.code:{},response.body:{}", response.code(), body);

        OrderApiResponse currentResult = JSON.parseObject(body, OrderApiResponse.class);
        Assert.notNull(currentResult, "call create order error,apiResponse must not be null");

        Assert.isTrue(StringUtils.isBlank(currentResult.getCode()) && StringUtils.isBlank(currentResult.getCodeMsg()) &&
                StringUtils.isNotNull(currentResult.getData()), "create order error,data is null");
        // 检查业务数据是否完整（重点校验pay_id）
        OrderData orderData = currentResult.getData();
        Assert.notNull(orderData, "create order error,data must not be null");
        Assert.notBlank(orderData.getPayId(), "create order error,payId must not be null");
        Assert.notBlank(orderData.getPapers().get(0).getPaperId(), "getPaperId must not be null");
        apiResponse.setData(orderData);
        return orderData.getPayId();
    }

    private void buildRequestHeaders(Request.Builder builder) {
        Random random = new Random();
        builder
                .addHeader("User-Agent", userAgents.get(random.nextInt(userAgents.size())))
//                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7")
                .addHeader("Connection", "keep-alive")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("Referer", "https://www.checkpass.net");
    }


    /**
     * 调用第三方论文上传接口
     *
     * @param paperAuthor 论文作者
     * @return 第三方返回的文件ID
     * @throws Exception 异常抛出给上层处理
     */
    private String callThirdPartyApi(String paperAuthor, MultipartFile paperFile,
                                     ThirdPartyResponse thirdPartyResponse) throws Exception {
        String externalApiUrl = "https://api.checkpass.net/call/upload/paper-upload-handler.php";
        String fileName = paperFile.getOriginalFilename();
        String os = System.getProperty("os.name").toLowerCase();
        String tempDir;
        if (os.contains("win")) {
            tempDir = env.getProperty("temp.file.dir.windows");
        } else {
            tempDir = env.getProperty("temp.file.dir.linux");
        }

        // 3. 验证配置是否为空（防止配置缺失）
        Assert.notBlank(tempDir, "tempDit must not be blank");

        // 4. 创建临时目录（跨系统路径处理）
        Path tempDirPath = Paths.get(tempDir);
        Files.createDirectories(tempDirPath);  // 自动处理路径分隔符（/或\）

        // 5. 生成唯一临时文件名（高并发不重复）
//        String uniqueFileName = fileName + "_" + UUID.randomUUID();
        String uniqueFileName = appendUuidToFileName(fileName);
        String removeFileSuffix = this.removeFileSuffix(fileName);

        Path tempFilePath = tempDirPath.resolve(uniqueFileName);  // 跨系统路径拼接
        File tempFile = tempFilePath.toFile();

        paperFile.transferTo(tempFile);

        try {
            // 构建请求参数
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("title", removeFileSuffix);
            params.add("author", paperAuthor);
            params.add("jane_name", "checkpass");
            params.add("files", new FileSystemResource(tempFile));

            // 设置请求头
            HttpHeaders headers = this.buildHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    externalApiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            // 校验响应状态
            Assert.isTrue(response.getStatusCode().is2xxSuccessful(),
                    "upload file code error!".concat(response.getStatusCode().toString()));

            logger.info("call paper-upload-handler.php code:{},result:{}", response.getStatusCode(), response.getBody());

            // 解析响应数据
            String responseBody = response.getBody();
            ThirdPartyResponse currentResponse = JSON.parseObject(responseBody, ThirdPartyResponse.class);

            // 校验响应结构
            Assert.notNull(currentResponse, "currentResponse must not be null");
            Assert.notEmpty(currentResponse.getFiles(), "currentResponse.getFile must not be null");

            FileInfo fileInfo = currentResponse.getFiles().get(0);
            Assert.notNull(fileInfo, "fileInfo must not be null");

            String thirdPartyFid = fileInfo.getFid();
            Assert.notBlank(thirdPartyFid, "thirdPartyFid must not be null");
            thirdPartyResponse.setFiles(currentResponse.getFiles());
            currentResponse.getFiles().get(0).setRemoveSuffixName(removeFileSuffix);
            return thirdPartyFid;
        } finally {
            // 清理临时文件（无论接口调用成功或失败，均尝试删除）
            if (tempFile.exists()) {  // 检查文件是否存在（避免删除不存在的文件）
                boolean deleteSuccess = tempFile.delete();
                if (deleteSuccess) {
                    logger.info("临时文件删除成功，路径：{}", tempFile.getAbsolutePath());
                } else {
                    logger.warn("临时文件删除失败，路径：{}", tempFile.getAbsolutePath());
                }
            } else {
                logger.info("临时文件不存在，无需删除，路径：{}", tempFile.getAbsolutePath());
            }
        }
    }

    private HttpHeaders buildHeaders() {
        // 在构建请求头部分新增以下逻辑
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 1. 随机User-Agent（新增）

        Random random = new Random();
        headers.set("User-Agent", userAgents.get(random.nextInt(userAgents.size())));

        // 2. 模拟浏览器基础头（新增）
        headers.set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8");
        headers.set("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
//        headers.set("Accept-Encoding", "gzip, deflate, br");
        headers.set("Connection", "keep-alive");
        headers.set("Referer", "https://www.checkpass.net"); // 模拟来源页面（根据目标网站首页调整）
        headers.set("Upgrade-Insecure-Requests", "1"); // 模拟浏览器升级HTTP到HTTPS

        return headers;
    }

    /**
     * 去除文件后缀（保留最后一个点之前的内容）
     *
     * @param originalFileName 原始文件名（如 "document.txt" 或 "image.tar.gz"）
     * @return 去除后缀后的文件名（如 "document" 或 "image.tar"）
     */
    public String removeFileSuffix(String originalFileName) {
        if (originalFileName == null || originalFileName.isEmpty()) {
            return originalFileName; // 空输入直接返回
        }

        int lastDotIndex = originalFileName.lastIndexOf('.');

        // 当最后一个点在开头（隐藏文件）或不存在时，保留原文件名
        if (lastDotIndex <= 0) {
            return originalFileName;
        }

        // 截取最后一个点之前的内容作为新文件名
        return originalFileName.substring(0, lastDotIndex);
    }


    public String appendUuidToFileName(String originalFileName) {
        // 查找最后一个点的位置（用于分离文件名和后缀）
        int lastDotIndex = originalFileName.lastIndexOf('.');

        String nameBody;  // 文件名主体（不含后缀）
        String fileSuffix; // 文件后缀（含点）

        if (lastDotIndex > 0) {
            // 存在有效后缀的情况（点不在开头）
            nameBody = originalFileName.substring(0, lastDotIndex);
            fileSuffix = originalFileName.substring(lastDotIndex);
        } else {
            // 无后缀或后缀无效的情况（如隐藏文件.xxx）
            nameBody = originalFileName;
            fileSuffix = "";
        }

        // 生成UUID（去掉中间的短横线）
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 拼接新文件名：主体 + "_" + UUID + 原后缀
        return nameBody + "_" + uuid + fileSuffix;
    }


    /**
     * 生成唯一文件名（原文件名+递增后缀）
     */
    private String generateUniqueFileName(String baseDir, String originalFileName) {
        int lastDotIndex = originalFileName.lastIndexOf('.');
        String baseName = (lastDotIndex == -1) ? originalFileName : originalFileName.substring(0, lastDotIndex);
        String extension = (lastDotIndex == -1) ? "" : originalFileName.substring(lastDotIndex);

        File baseDirFile = new File(baseDir);
        if (!baseDirFile.exists()) {
            baseDirFile.mkdirs();
        }

        String candidateName = originalFileName;
        int counter = 1;
        while (new File(baseDirFile, candidateName).exists()) {
            candidateName = String.format("%s_%d%s", baseName, counter, extension);
            counter++;
        }
        return candidateName;
    }

    /**
     * 获取文件上传基础路径（可根据实际配置调整）
     */
    private String getUploadPath() {
        // 示例：从配置文件读取上传路径，实际项目中建议使用@Value注入
        return "D:/upload/papers/";
    }

    /**
     * 修改checkpass论文
     */
    @RequiresPermissions("system:pass:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        PaperCheckPass paperCheckPass = paperCheckPassService.selectPaperCheckPassById(id);
        mmap.put("paperCheckPass", paperCheckPass);
        return prefix + "/edit";
    }

    /**
     * 修改保存checkpass论文
     */
    @RequiresPermissions("system:pass:edit")
    @Log(title = "checkpass论文", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PaperCheckPass paperCheckPass) {
        return toAjax(paperCheckPassService.updatePaperCheckPass(paperCheckPass));
    }

    /**
     * 删除checkpass论文
     */
    @RequiresPermissions("system:pass:remove")
    @Log(title = "checkpass论文", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(paperCheckPassService.deletePaperCheckPassByIds(ids));
    }


    public static void main(String[] args) throws IOException {
        // 构建 multipart/form-data 请求体（使用 OkHttp3 的 MultipartBody）
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); // 类型设置方式变更
        String url =
                "https://api.checkpass.net/an/checkorder/preCreateMulti?_user_token=oh6bS11bYGhfw5GZOW68fbQrAAw%3D";
        // 构建 papers 数组参数（保持原始错误键名）
        JSONArray jsonArray = new JSONArray();
        JSONObject paper = new JSONObject();
        paper.put("file_fid", "32608136");
        paper.put("title", "基于springBoot的健康食谱管理系统 - 副本_ad1121310af74343b5ca2c06b542c5da");
        paper.put("author", "ce");
        paper.put("content_type", "file_fid"); // 保留原始参数格式
        jsonArray.add(paper);

        // 添加 form-data 参数（完全保持原始错误键名）
        multipartBuilder.addFormDataPart("good id", "124913");
        multipartBuilder.addFormDataPart("jane name", "checkpass");
//        multipartBuilder.addFormDataPart("papers", jsonArray.toJSONString()););
        multipartBuilder.addFormDataPart("papers[0][file_fid]", "32608136");
        multipartBuilder.addFormDataPart("papers[0][title]",
                "基于springBoot的健康食谱管理系统 - 副本_ad1121310af74343b5ca2c06b542c5da");
        multipartBuilder.addFormDataPart("papers[0][author]", "ce");
        multipartBuilder.addFormDataPart("papers[0][content_type]", "file_fid");


        // 构建请求对象（OkHttp3 的 Request 构建方式）
        Request request = new Request.Builder()
                .url(url)
                .post(multipartBuilder.build()) // 请求体构建方式变更
                .addHeader("User-Agent", "OkHttp/3.14.9") // 更新为 OkHttp3 标准 UA
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String body = response.body().string();
        System.out.println();


//        String url = "https://api.checkpass.net/an/checkorder/preCreateMulti?_user_token=oh6bS11bYGhfw5GZOW68fbQrAAw%3D";
//
//        /**
//         * 设置超时时间
//         */
//        OkHttpClient okHttpClient = new OkHttpClient
//                .Builder()
//                .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
//                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
//                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
//                .build();
//
//        JSONArray jsonArray = new JSONArray();
//        JSONObject paper = new JSONObject();
//        paper.put("file_fid", 32608136);
//        paper.put("title", "基于springBoot的健康食谱管理系统 - 副本_ad1121310af74343b5ca2c06b542c5da");
//        paper.put("author", "ce");
//        paper.put("content_type", "file_fid"); // 保留原始参数格式
//        jsonArray.add(paper);
//        //表单数据参数填入
//        RequestBody body = new FormBody.Builder().add(
//                "good id", "124913").add("jane name", "checkpass")
////                .add("papers", jsonArray.toJSONString())
//                        .build();
//
//        Request request = new Request.Builder()
//                .url(url)
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//        try {
//            Response response = call.execute();
//
//            String result = response.body().string();//得到数据
//            JSONObject jsonObject = JSONObject.parseObject(result);//转为JSON格式
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }
}
